import { RouteObject } from '@/routes/interface';

export const seachRoute = (path: string, routes: RouteObject[]): RouteObject => {
  let resule: RouteObject = {};
  for (let item of routes) {
    if (item.path === path) return item;
    if (item.children) {
      const res = seachRoute(path, item.children);
      if (Object.keys(res).length) return res;
    }
  }
  return resule;
};

// 双重递归，找出所有面包屑生成对象存储到redux中
export const findAllBreadcrumb = (menuList: Menu.MenuOptions[]): { [key: string]: any } => {
  let handleBreadcrumbList: any = {};
  const loop = (menuItem: Menu.MenuOptions) => {
    if (menuItem?.children && menuItem?.children?.length > 0) {
      menuItem.children.forEach((item: Menu.MenuOptions) => {
        loop(item);
      });
    } else {
      handleBreadcrumbList[menuItem.path!] = getBreadcrumbList(menuItem.path, menuList);
    }
  };
  menuList.forEach((item) => {
    loop(item);
  });
  return handleBreadcrumbList;
};

// 递归menuList，获取path对应的lable及父lable
export const getBreadcrumbList = (path: string | undefined, menuList: Menu.MenuOptions[]) => {
  let breadcrumbList: any[] = [];
  try {
    const loop = (menuItem: Menu.MenuOptions) => {
      breadcrumbList.push(menuItem);
      if (menuItem.path === path) {
        throw new Error('GOT IT!');
      }
      if (menuItem?.children && menuItem.children.length > 0) {
        for (let i = 0; i < menuItem.children.length; i++) {
          loop(menuItem.children[i]);
        }
        // 当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
        breadcrumbList.pop();
      } else {
        // 找到叶节点时，删除路径当中的该叶子节点
        breadcrumbList.pop();
      }
    };
    for (let i = 0; i < menuList.length; i++) {
      loop(menuList[i]);
    }
  } catch (e) {
    return breadcrumbList.map((item) => item.label);
  }
};
